package com.golddaymicromall.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.activity.R;
import com.golddaymicromall.activity.salemanager.StoreUpgradeConfirmActivity;
import com.golddaymicromall.adapter.Sale_StoreUpgradeAdapter;
import com.golddaymicromall.bean.ProductInfo;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;

/**
 * Created by Administrator on 2016/3/4 0004.
 */
public class Sale_StoreUpgradeFragment extends Fragment implements View.OnClickListener {
    private View view;
    private List<ProductInfo> list = new ArrayList<ProductInfo>();
    private List<ProductInfo> listFlag;
    private ListView mLv;
    private Sale_StoreUpgradeAdapter adapter;
    private String customerid;
    private TextView upgradeAllPrice;
    private TextView upgradeSettlement;
    private float allPrice;
    private float RealPay;

    private LinearLayout mUpgradeLvLayout;
    private LinearLayout mUpgradeBar;
    private TextView mUpgradeTipsVal;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_storeupgrade, container, false);
        initView();
        attemptShouYitop();
        return view;
    }

    private void initView() {
        mLv = (ListView) view.findViewById(R.id.storeupgrade_listview);
        upgradeAllPrice = (TextView) view.findViewById(R.id.upgrade_allprice);
        upgradeSettlement = (TextView) view.findViewById(R.id.upgradesettlement);
        mUpgradeLvLayout = (LinearLayout) view.findViewById(R.id.upgrade_lvlayout);
        mUpgradeBar = (LinearLayout) view.findViewById(R.id.upgrade_bar);
        mUpgradeTipsVal = (TextView) view.findViewById(R.id.upgrade_tipval);
        upgradeSettlement.setOnClickListener(this);
        getActInfo();
    }

    private void plusPrice(int selectId) {
        allPrice = 0f;
        RealPay = 0f;
        listFlag = new ArrayList<ProductInfo>();
        listFlag.add(list.get(selectId));
        allPrice = Float.valueOf(list.get(selectId).getPrice());
        RealPay = Float.valueOf(list.get(selectId).getPv());
        upgradeAllPrice.setText("合计:￥" + allPrice);
        upgradeSettlement.setText("结算（" + RealPay + ")");
    }

    private void attemptShouYitop() {
        //获取本地数据
        customerid = SPUtils.get(getActivity(), "Id", "").toString();
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.order.fristshoping");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("customerid", customerid);
        form.put("orderType", "2");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    list = new ArrayList<ProductInfo>();
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(getActivity(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
                            mUpgradeLvLayout.setVisibility(View.GONE);
                            mUpgradeBar.setVisibility(View.GONE);
                            mUpgradeTipsVal.setVisibility(View.VISIBLE);
                        } else {
                            list = JSON.parseArray(result, ProductInfo.class);
                            adapter = new Sale_StoreUpgradeAdapter(list, getActivity());
                            mLv.setAdapter(adapter);
                            plusPrice(0);
                            adapter.setOncheckChanged(selectID -> {
                                adapter.setSelectID(selectID);//选中位置
                                plusPrice(selectID);
                                adapter.notifyDataSetChanged();        //刷新适配器
                            });
                        }
                    } else {
                        Toast.makeText(getActivity(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                },throwable -> {
                    throwable.printStackTrace();
                });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.upgradesettlement:
                if ("".equals(upgradeAllPrice.getText())) {
                    Toast.makeText(getActivity(), "请点击要选择的产品", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent2Confirm = new Intent(getActivity(), StoreUpgradeConfirmActivity.class);
                intent2Confirm.putExtra("listFlag", (Serializable) listFlag);
                startActivity(intent2Confirm);
                break;
        }
    }

    public void getActInfo() {
        String shopGrade = SPUtils.get(getActivity(), "shop_Grade", "").toString();
        String id = SPUtils.get(getActivity(), "Id", "").toString();
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.order.getactivity");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("shopgrade", shopGrade);
        form.put("ordertype", "2");
        form.put("id", id);
        form.put("ob", "1");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(),RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            SPUtils.put(getContext(), "secondAct", "0");
                            SPUtils.put(getContext(), "secondActPro", "0");
                        } else if ("null".equals(result) || result.contains("[]")) {
                            SPUtils.put(getContext(), "secondAct", "0");
                            SPUtils.put(getContext(), "secondActPro", "0");
                        } else {
                            SPUtils.put(getContext(), "secondAct", result);
                            attemptActProductInfoTask();
                        }
                    } else {
                        Toast.makeText(getContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                },throwable -> {
                    throwable.printStackTrace();
                });
    }

    public void attemptActProductInfoTask() {
        String shopGrade = SPUtils.get(getActivity(), "shop_Grade", "").toString();
        String id = SPUtils.get(getActivity(), "Id", "").toString();
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.order.getactivity");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("shopgrade", shopGrade);
        form.put("ordertype", "2");
        form.put("id", id);
        form.put("ob", "2");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(getContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result) || result.contains("[]")) {
                            SPUtils.put(getContext(), "secondActPro", "0");
                        } else {
                            SPUtils.put(getContext(), "secondActPro", result);
                        }
                    } else {
                        Toast.makeText(getContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                });
    }
}
